<template>
  <div class="author-form">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>{{ isEdit ? '编辑作者' : '添加作者' }}</h2>
      <el-button @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
        返回列表
      </el-button>
    </div>

    <!-- 表单区域 -->
    <div class="form-section">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        size="large"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="作者姓名" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入作者姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国籍" prop="nationality">
              <el-input
                v-model="form.nationality"
                placeholder="请输入国籍"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱地址"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="form.birthDate"
                type="date"
                placeholder="请选择出生日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="个人网站" prop="website">
              <el-input
                v-model="form.website"
                placeholder="请输入个人网站地址"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :value="1">正常</el-radio>
                <el-radio :value="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="头像" prop="avatarImage">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <img v-if="form.avatarImage" :src="form.avatarImage" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="upload-tip">支持 jpg、png 格式，文件大小不超过 2MB</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="作者简介" prop="biography">
              <el-input
                v-model="form.biography"
                type="textarea"
                :rows="4"
                placeholder="请输入作者简介"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 操作按钮 -->
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
                <el-icon><Check /></el-icon>
                {{ isEdit ? '更新' : '保存' }}
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button @click="goBack">
                <el-icon><Close /></el-icon>
                取消
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Plus, Check, Refresh, Close } from '@element-plus/icons-vue'
import authorApi from '@/api/author'

const router = useRouter()
const route = useRoute()

// 响应式数据
const formRef = ref()
const submitLoading = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 表单数据
const form = reactive({
  id: null,
  name: '',
  nationality: '',
  email: '',
  birthDate: '',
  website: '',
  status: 1,
  avatarImage: '',
  biography: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入作者姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  nationality: [
    { max: 50, message: '国籍长度不能超过 50 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
    { max: 100, message: '邮箱长度不能超过 100 个字符', trigger: 'blur' }
  ],
  website: [
    { type: 'url', message: '请输入正确的网站地址', trigger: 'blur' },
    { max: 200, message: '网站地址长度不能超过 200 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  biography: [
    { max: 500, message: '简介长度不能超过 500 个字符', trigger: 'blur' }
  ]
}

// 获取作者详情
const getAuthorDetail = async (id) => {
  try {
    const result = await authorApi.getById(id)
    if (result) {
      Object.keys(form).forEach(key => {
        if (result[key] !== undefined) {
          form[key] = result[key]
        }
      })
      
      // 处理日期格式
      if (result.birthDate) {
        form.birthDate = new Date(result.birthDate).toISOString().split('T')[0]
      }
    }
  } catch (error) {
    ElMessage.error('获取作者详情失败: ' + error.message)
    goBack()
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = (options) => {
  // 这里应该调用文件上传接口
  // 暂时使用 FileReader 预览
  const reader = new FileReader()
  reader.onload = (e) => {
    form.avatarImage = e.target.result
  }
  reader.readAsDataURL(options.file)
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) return

    submitLoading.value = true

    // 准备提交数据
    const submitData = { ...form }
    
    // 处理日期格式
    if (submitData.birthDate) {
      submitData.birthDate = new Date(submitData.birthDate).toISOString()
    }

    if (isEdit.value) {
      // 更新作者
      await authorApi.update(submitData)
      ElMessage.success('更新作者成功')
    } else {
      // 添加作者
      delete submitData.id
      await authorApi.add(submitData)
      ElMessage.success('添加作者成功')
    }

    goBack()
  } catch (error) {
    ElMessage.error((isEdit.value ? '更新' : '添加') + '作者失败: ' + error.message)
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const handleReset = () => {
  formRef.value.resetFields()
  if (isEdit.value) {
    getAuthorDetail(route.params.id)
  } else {
    Object.keys(form).forEach(key => {
      form[key] = key === 'status' ? 1 : (key === 'id' ? null : '')
    })
  }
}

// 返回列表
const goBack = () => {
  router.push('/author')
}

// 组件挂载时的操作
onMounted(() => {
  if (isEdit.value) {
    getAuthorDetail(route.params.id)
  }
})
</script>

<style scoped>
.author-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-section {
  background: #fff;
  padding: 30px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.avatar-uploader {
  display: inline-block;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 120px;
  height: 120px;
  object-fit: cover;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}
</style>
